using SDK.Scripts.Utils;
using System;
using System.Net;
using System.Net.Sockets;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;

namespace Brick
{
	public class CompatibilityIP
	{
#if UNITY_IPHONE && !UNITY_EDITOR
	[DllImport("__Internal")]
	private static extern string getIPv6(string host, string port);
#endif

		private static string getIPv6ByCS(string mHost, string mPort)
		{
#if UNITY_IPHONE && !UNITY_EDITOR
		string mIPv6 = getIPv6(mHost, mPort);
		return mIPv6;
#else
			return mHost + "&&ipv4";
#endif
		}

		private static string GetIPv6(string host, string port)
		{
			return host + "&&ipv4";
		}

		public static void GetIpType(string serverIp, string serverPort, out string newServerIp, out AddressFamily newServerAddressFamily)
		{
			newServerAddressFamily = AddressFamily.InterNetwork;
			newServerIp = serverIp;
			long result = 0L;
			if (long.TryParse(serverIp.Replace(".", string.Empty), out result))
			{
				try
				{
					string iPv = GetIPv6(serverIp, serverPort);
					if (!string.IsNullOrEmpty(iPv))
					{
						string[] array = Regex.Split(iPv, "&&");
						if (array.Length >= 2)
						{
							string a = array[1];
							if (a == "ipv6")
							{
								newServerIp = array[0];
								newServerAddressFamily = AddressFamily.InterNetworkV6;
							}
						}
					}
				}
				catch (Exception ex)
				{
					Debuger.LogError(ex.Message);
				}
				return;
			}
			IPAddress[] hostAddresses = Dns.GetHostAddresses(serverIp);
			if (hostAddresses.Length > 0 && hostAddresses[0].AddressFamily == AddressFamily.InterNetworkV6)
			{
				newServerIp = hostAddresses[0].ToString();
				newServerAddressFamily = AddressFamily.InterNetworkV6;
			}
		}
	}
}

